/*******************************************************************************
 * Copyright 2013 Mindaugas Idzelis
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package incontrol.server;

import incontrol.core.Config;
import incontrol.plugin.Plugin;
import incontrol.plugin.protocol.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Map;

import org.cometd.server.BayeuxServerImpl;
import org.xeustechnologies.jcl.JarClassLoader;
import org.xeustechnologies.jcl.JclObjectFactory;
import org.xeustechnologies.jcl.context.DefaultContextLoader;
import org.xeustechnologies.jcl.context.JclContext;
import org.yaml.snakeyaml.Yaml;

public class Startup {

	public static void main(String[] args) throws Exception {
		new DefaultContextLoader(new JarClassLoader()).loadContext();
		JarClassLoader loader = JclContext.get();
		Thread.currentThread().setContextClassLoader(loader);

		Yaml yaml = new Yaml();
		if (args.length != 1) {
			System.out.println("Must specify configuration file");
		}
		Map<String, Object> c = null;
		try {
			c = (Map<String, Object>) yaml.load(new FileInputStream(new File(
					args[0])));
		} catch (Exception e) {
			System.out.println("Error reading config");
			e.printStackTrace();
		}

		Config config = new Config(c);
		List<String> plugins = (List<String>) config.getList("Plugins");
		if (plugins != null) {
			for (String string : plugins) {
				File f = new File(string);
				if (f.isDirectory()) {
					loader.add(f.getCanonicalPath() + File.separatorChar);
				} else {
					loader.add(f.getCanonicalPath());
				}
			}
		}
		// TODO: make this generic

		IncontrolServer server = new IncontrolServer();
		server.startup(config);
		BayeuxServerImpl bayeuxServerImpl = server.getBayeuxServer();
		{
			EventBus e = new EventBus(bayeuxServerImpl.newLocalSession("ts"));
			Plugin p1 = (Plugin) JclObjectFactory.getInstance().create(
					JclContext.get(), "pure.teamspeak.PureTeamSpeak");
			p1.preInit(config, e);
		}
		{
			EventBus e = new EventBus(
					bayeuxServerImpl.newLocalSession("balancer"));
			Plugin p1 = (Plugin) JclObjectFactory.getInstance().create(
					JclContext.get(), "pure.balancer.PureBalancer");
			p1.preInit(config, e);
		}

	}
}
